{#
    Form elements 
#}

{% macro LabelFor( property, value ) %}
    {% if value is not null %}
        <label for="{{ property }}">{{ value.label }}</label>
    {% endif %}
{% endmacro %}

{% macro DisplayFor( property, value ) %}    
    {% if value is not null %}
        <span>{{ value.data }}</span>
    {% endif %}
{% endmacro %}

{% macro TextBoxFor( property, value ) %}
    {% if value is not null %}
        <input type="{{ value.type | default('text') }}" id="{{ value.id ?: property }}" name="{{ property }}" value="{{ value.data }}"
               {% for attribute in value.attributes | keys %}
                   {{ ' ' ~ attribute ~ '=' ~ value.attributes[attribute]  }}
               {% endfor %}
               >
    {% endif %}
{% endmacro %}

{% macro HiddenFor( property, value ) %}
    <input type="hidden" id="{{ property }}" name="{{ property }}" value="{{ value }}">
{% endmacro %}

{% macro SelectFor( property, value ) %}
    <select id="{{ property }}" name="{{ property }}" size="1"
            {% for attribute in value.attributes | keys %}
                {{ (' ' ~ attribute ~ '="' ~ value.attributes[attribute] ~ '"') | raw }}
            {% endfor %}
            >
        {% for item in value.data %}
            {% if not loop.last %}
                <option value="{{ item[0] }}"{{ value.selection == item[0] ? ' selected' }}>{{ item[1] }}</option>
            {% endif %}
        {% endfor %}
    </select>
{% endmacro %}

{% macro Options( data, selection ) %}
{% endmacro %}

{#
    Form fields
#}

{% macro Field(model, property, class, editable, selectable) %}
    {% import 'macros/table.twig' as table %}
    {% import _self as form %}
    {% set class = class is not null ? ' ' ~ class %}
    {{ table.td(form.LabelFor(property, model[property]), 'label field' ~ (model[property] is null ? ' empty') ~ class ) }}
    {% if editable %}
        {% if selectable or model[property].type == 'select' %}
            {{ table.td(form.SelectFor(property, model[property]), 'td_data edit' ~ (model[property] is null ? ' empty') ~ class ) }}              
        {% else %}
            {{ table.td(form.TextBoxFor(property, model[property]), 'td_data edit' ~ (model[property] is null ? ' empty') ~ class ) }}
        {% endif %}
    {% else %}
        {{ table.td(form.DisplayFor(property, model[property]), 'td_data field' ~ class ) }}
    {% endif %}
{% endmacro %}

{% macro Fields(model, class, editable, selectable, columns) %}
    {% import _self as userform %}
    {% for properties in model | keys | batch( columns | default(2) ) %}
        <tr>
            {% for property in properties %}
                {{ userform.Field(model, property, class, editable, selectable) }}
            {% endfor %}
        </tr>
    {% endfor %}
{% endmacro %}